<script setup>
import { ref, watch, computed, inject } from 'vue'
import { ElMessage } from 'element-plus'
import { useAddTaskService, useEditTaskService, useDeleteTaskService, useFinishTaskService } from '@/api/task'
import { useUserStore } from '@/stores'
const userStore = useUserStore()
// 从父组件（LayoutPage）注入刷新方法
const refreshData = inject('refreshData', () => {})
// 传给父组件提醒刷新分类列表事件
const emit = defineEmits(['refreshTasks'])
// 接收动态路由传递的任务分类名称，进行渲染
const props = defineProps({
  classifyId: Number,
  classifyName: String,
  // 从父组件获取任务列表
  taskList: Array
})
// 控制任务展开/收起，默认展开
// 控制未完成任务
const toFinish_isShow = ref(true)
// 控制已完成任务
const finished_isShow = ref(true)
// 默认显示分类名称
const otherClassifyName = ['今天', '最近七天', '全部事项', '未完成', '已完成']
const defaultClassifyName = ref(otherClassifyName.includes(props.classifyName) ? '' : props.classifyName)
console.log('默认显示分类名称:' + defaultClassifyName.value)
// 默认分类id
const defaultClassifyId = ref(props.classifyId || 0)
console.log('默认分类id:' + defaultClassifyId.value)
// 任务列表
const taskList = ref(props.taskList)
console.log('当前任务列表:' + JSON.stringify(taskList.value))
// 未完成任务列表
const toFinishList = ref(taskList.value.filter(item => !item.isDeleted && !item.isFinished))
// 未完成任务数量
const toFinishCnt = computed(() => toFinishList.value.length)
// 已完成任务列表
const finishedList = ref(taskList.value.filter(item => !item.isDeleted && item.isFinished))
// 已完成任务数量
const finishedCnt = computed(() => finishedList.value.length)
// 完成任务事件
const handleFinishedClick = async (id) => {
  // 执行完成任务接口
  const res = await useFinishTaskService({ id })
  if(res.data.status === 0) {
    ElMessage.success('任务完成啦！')
  } else {
    ElMessage.error('任务完成失败！')
  }
  // 提醒父组件更新任务列表
  emit('refreshTasks')
  // 提醒父组件更新任务列表
  refreshData()
  // 前端立即响应，防止后端响应时间过长，任务完成，将isFinished改为true
  taskList.value.forEach(item => {
    if(item.id === id) {
      item.isFinished = true
    }
  })
}
// 拖动开始
const dragstart = (taskId, event) => {
  event.dataTransfer.setData("text", taskId)
  console.log("您已成功拖动任务" + taskId)    
}
// 进行放置（需要优化：未完成任务拖拽到已完成区域时自动变成已完成任务）
const drop = (targetId, event) => {
  const draggedId = event.dataTransfer.getData("text")  // 获取被拖拽任务的id
  // 使用Number()将字符串转换为数字，避免字符串比较
  const targetIndex = taskList.value.findIndex(task => Number(task.id) === Number(targetId))
  console.log('放置时draggedId：' + draggedId)
  const draggedIndex = taskList.value.findIndex(task => Number(task.id) === Number(draggedId))
  // 添加防护检查
  if (draggedIndex === -1 || targetIndex === -1) {
    console.error('找不到对应的任务', { draggedId, targetId, 
      draggedType: typeof draggedId, 
      targetType: typeof targetId 
    })
    return
  }
  // 获取拖拽的任务
  const draggedTask = taskList.value[draggedIndex]
  // 在 taskList 中调整顺序
  taskList.value.splice(draggedIndex, 1);
  taskList.value.splice(targetIndex, 0, draggedTask)
  console.log('拖拽放置后的taskList：' + JSON.stringify(taskList.value))
}
// 放置位置 - 阻止默认事件,即允许放置
const dragover = (event) => {
  event.preventDefault()
}
// 控制编辑框显隐,默认隐藏
const editCardVisible = ref(false)
// 表单数据
const formData = ref({
  title: '',
  classify_id: 0,  // 默认值为 0，避免数据库错误
  classify_name: '',
  finishDate: '',
})
// 点击输入框添加新任务事件
const handleClickInp = () => {
  editCardVisible.value = true
  formData.value = {
    title: '',
    classify_id: defaultClassifyId.value,
    classifyName: defaultClassifyName.value,
    finishDate: '',
  }
}
// 添加-编辑任务事件
const addEditTask = async (id) => {
  // 判断是否传入id，有id即为编辑任务，反之为添加任务
  if (id) {
    console.log('执行编辑任务,任务id:' + id)
    // 执行编辑任务逻辑
    const res = await useEditTaskService({
      id: id,
      title: formData.value.title,
      classify_id: formData.value.classify_id,
      classify_name: formData.value.classify_name,
      finish_date: formData.value.finishDate,
    })
    if(res.data.status === 0) {
      ElMessage.success('任务编辑成功！')
    } else {
      ElMessage.error('任务编辑失败！')
    }
  } else {
    console.log('执行添加任务')
    // 执行添加任务逻辑
    if (formData.value.title) {
      // 添加新任务至列表
      const res = await useAddTaskService({
        user_id: userStore.userId,
        title: formData.value.title,
        classify_id: formData.value.classify_id || 0,  // 默认提供0
        classify_name: formData.value.classify_name,
        isFinished: 0,
        finish_date: formData.value.finishDate,
        create_date: new Date().toISOString(),
        isDeleted: 0,
      })
      console.log('添加任务事件, res:' + JSON.stringify(res))
      if (res.data.status === 0) { 
        ElMessage.success('任务添加成功！')
      } else {
        ElMessage.error('任务添加失败！')
      }
    }else {
      ElMessage.error('任务标题不能为空')
    }
    // 清空表单数据
    formData.value = {
      title: '',
      classify_id: '',
      classify_name: '',
      finishDate: '',
    }
  }
  // 关闭编辑框
  editCardVisible.value = false
  // 提醒父组件刷新分类列表
  emit('refreshTasks')
  // 提醒父组件刷新任务列表
  refreshData()
}
// 编辑任务前回显表单数据事件
const editTask = (id) => {
  editCardVisible.value = true
  // 获取原任务信息
  const originalTask = taskList.value.find(item => item.id === id)
  // 回显表单数据
  formData.value = {
    id: originalTask.id,  // 存储任务id,编辑任务时使用
    title: originalTask.title,
    classify_id: originalTask.classify_id,
    classify_name: originalTask.classify_name,
    finishDate: originalTask.finish_date,
  }
  console.log('编辑任务事件, 回显表单数据' + JSON.stringify(formData.value))
}
// 删除任务事件
const deleteTask = async (id) => {
  const res = await useDeleteTaskService({ id })
  if(res.data.status === 0) {
    ElMessage.success('任务删除成功！')
  } else {
    ElMessage.error('任务删除失败！')
  }
  // 前端立即更新任务列表，防止后端响应时间长
  taskList.value = taskList.value.filter(task => task.id !== id)
  // 提醒父组件刷新任务列表
  emit('refreshTasks')
  // 提醒父组件刷新任务列表
  refreshData()
  console.log('删除后taskList.value：' + JSON.stringify(taskList.value))
}
// 监听父组件传来的分类名称变化
watch(
  [() => props.classifyName,
  () => props.classifyId],
  ([newClassifyName, newClassifyId]) => {
    defaultClassifyName.value = otherClassifyName.includes(newClassifyName) ? '' : props.classifyName
    defaultClassifyId.value = newClassifyId
  },
  {
    immediate: true
  }
)
// 监听父组件传来的任务列表变化
watch(
  () => props.taskList,
  (newTaskList) => {
    console.log('AddTasksContent: 接收到新的任务列表',props.taskList)
    taskList.value = Array.isArray(newTaskList) ? [...newTaskList] : []
    // 立即更新未完成和已完成列表
    toFinishList.value = taskList.value.filter(item => !item.isDeleted && !item.isFinished)
    finishedList.value = taskList.value.filter(item => !item.isDeleted && item.isFinished)
  },
  {
    immediate: true,
    deep: true
  }
)
// 监听列表变化，实时修改数量
watch(
  [taskList],
  () => {
    console.log('列表发生变化了' + JSON.stringify(taskList.value))
    // 延时更新
    setTimeout(() => {
      toFinishList.value = taskList.value.filter(item => !item.isDeleted && !item.isFinished)
      finishedList.value = taskList.value.filter(item => !item.isDeleted && item.isFinished)
    }, 500)
  },
  {
    deep: true
  }
)
</script>

<template>
  <div class="list">
    <!-- 顶部 -->
    <div class="list-header">
      <div class="left">
        <div class="iconfont">&#xe790;</div>
        <div class="header-title">{{ classifyName }}</div>
      </div>
    </div>
    <!-- 添加任务输入框 -->
    <div class="add-task">
      <span @click="handleClickInp"  class="tips">+ 添加任务</span>
    </div>
    <!-- 编辑对话框 -->
    <EditTaskCard 
    v-model:editCardVisible="editCardVisible" 
    v-model:formData="formData"
    @confirm="addEditTask"
    :defaultClassifyName="defaultClassifyName"
    />
    <!-- 任务部分 -->
    <div class="tasks">
      <!-- 未完成 -->
      <div class="toFinish">
        <div class="section-header" :class="{'collapsed': !toFinish_isShow}">
          <!-- 展开任务箭头 -->
          <span class="iconfont" 
          v-if="toFinish_isShow"
          @click="toFinish_isShow = false"
          >
            &#xe649;
          </span>
          <!-- 任务收起箭头 -->
          <span class="iconfont" 
          v-else
          @click="toFinish_isShow = true"
          >
            &#xe62b;
          </span>
          <div class="title">未完成</div>
          <!-- 任务数量 -->
          <span class="count">{{ toFinishCnt }}</span>
        </div>
        <!-- 任务列表 -->
        <div class="task-container" v-if="toFinish_isShow">
          <div draggable="true" 
          @dragstart="dragstart(item.id, $event)"
          @drop.prevent="drop(item.id, $event)"
          @dragover.prevent="dragover"
          v-for="(item, index) in toFinishList" 
          :key="item.id" 
          class="todo-card"
          >
            <!-- 代办序号 -->
            <div class="number">{{ index + 1 }}</div>
            <!-- 编辑区域 -->
            <div class="edit-block">
              <h3 class="title">{{ item.title}}</h3>
              <div class="classify">分类：{{ item.classify_name || '无'   }}</div>
              <div class="finish-date">
                <span class="iconfont">&#xe61f;</span>
                <span>{{ item.finish_date }}</span>
              </div>
            </div>
            <!-- 图标区域 -->
            <div class="icon-box">
              <div class="icon-yes">
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="任务完成"
                  placement="bottom-start"
                >
                  <div @click="handleFinishedClick(item.id)" class="iconfont" v-if="!item.isFinished"></div>
                </el-tooltip>
                <div class="iconfont" v-if="item.isFinished">&#xe613;</div>
              </div>
              <div class="icon-other">
                <!-- 拖动排序按钮 -->
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="拖动排序"
                  placement="bottom-start"
                >
                  <div class="iconfont">&#xe80f;</div>
                </el-tooltip>
                <!-- 编辑任务按钮 -->
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="编辑任务"
                  placement="bottom-start"
                >
                  <div class="iconfont" plain @click="editTask(item.id)">&#xe609;</div>
                </el-tooltip>
                <!-- 删除按钮 -->
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="删除任务"
                  placement="bottom-start"
                >
                  <div class="iconfont">
                    <DeleteTaskBtn @delete-click="deleteTask(item.id)" />
                  </div>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 已完成 -->
      <div class="finished">
        <div class="section-header" :class="{'collapsed': !finished_isShow}">
          <!-- 展开任务箭头 -->
          <span class="iconfont" 
          v-if="finished_isShow"
          @click="finished_isShow = false"
          >
            &#xe649;
          </span>
          <!-- 任务收起箭头 -->
          <span class="iconfont" 
          v-else
          @click="finished_isShow = true"
          >
            &#xe62b;
          </span>
          <div class="title">已完成</div>
          <!-- 任务数量 -->
          <span class="count">{{ finishedCnt }}</span>
        </div>
        <!-- 任务列表 -->
        <div class="task-container" v-if="finished_isShow">
          <div draggable="true" 
          @dragstart="dragstart(item.id, $event)"
          @drop.prevent="drop(item.id, $event)"
          @dragover.prevent="dragover"
          v-for="(item, index) in finishedList" 
          :key="item.id" 
          class="todo-card"
          >
            <!-- 代办序号 -->
            <div class="number">{{ index + 1 }}</div>
            <!-- 编辑区域 -->
            <div class="edit-block">
              <h3 class="title">{{ item.title}}</h3>
              <div class="classify">分类：{{ item.classify_name }}</div>
              <div class="finish-date">
                <span class="iconfont">&#xe61f;</span>
                <span>{{ item.finish_date }}</span>
              </div>
            </div>
            <!-- 图标区域 -->
            <div class="icon-box">
              <div class="icon-yes">
                <div @click="handleFinishedClick(item.id)" class="iconfont" v-if="!item.isFinished"></div>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="任务已经完成了"
                  placement="bottom-start"
                >
                  <div class="iconfont" v-if="item.isFinished">&#xe613;</div>
                </el-tooltip>
              </div>
              <div class="icon-other">
                <!-- 拖动排序按钮 -->
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="拖动排序"
                  placement="bottom-start"
                >
                  <div class="iconfont">&#xe80f;</div>
                </el-tooltip>
                <!-- 删除按钮 -->
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="删除任务"
                  placement="bottom-start"
                >
                  <div class="iconfont">
                    <DeleteTaskBtn @delete-click="deleteTask(item.id)" />
                  </div>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>

<style lang="less" scoped>
.list {
  width: 100%;
  height: 100vh;
  display: flex;
  padding-bottom: 30px;
  flex-direction: column;
  border-right: 1px solid #ccc;
  overflow: auto;

  .list-header {
    margin: 20px;
    height: 40px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    .left {
      display: flex;
      align-items: center;

      .iconfont {
        margin-right: 10px;
        font-size: 23px;
        color: #a3a3a3;
        cursor: pointer;
      }

      .header-title {
        font-size: 22px;
        font-weight: 700;
      }
    }
  }

  .add-task {
    display: flex;
    align-items: center;
    width: 40rem;
    height: 2.5rem;
    margin: 0 20px 20px;
    padding: 0 10px;
    border-radius: 5px;
    border: 1px solid #466ff5;

    .tips {
      width: 100%;
      height: 1.5rem;
      border: none;
      line-height: 1.5rem;
      font-size: 0.9rem;
      color: #e0dede;
    }

    .iconfont {
      font-size: 16px;
      cursor: pointer;
    }
  }

  // 重构部分
  .tasks {
    overflow: auto;

    .toFinish,
    .finished {
      margin: 0 20px;
      
      .section-header {
        height: 2.5rem;
        display: flex;
        align-items: center;
        margin-bottom: 1.2rem;
        border-radius: 0.4rem;
        font-size: 0.95rem;
        color: #a3a3a3;

        // 任务收起时的样式
        &.collapsed {
          background-color: #f1f1f1;
        }

        .title {
          margin: 0 5px;
          color: #000;
          font-weight: 700;
        }
      }

      .task-container {
        display: flex;
        flex-wrap: wrap;
        align-content: flex-start;

        .todo-card {
          width: 14rem;
          height: 14rem;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          margin: 0 3rem 3rem 0;
          padding: 1rem;
          background-color: #a1d9ff;
          border-radius: 1.5rem;
          transition: all 0.3s ease-in-out;

          &:hover {
            transform: translateY(-1rem);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.2);
          }

          .number {
            font-family: "round";
            font-size: 1.3rem;
            font-weight: 600;
          }

          .edit-block {
            width: 100%;
            // height: 60%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;

            .title {
              width: 100%;
              max-height: 3.75rem; // 3行文本的高度
              font-size: 1.25rem;
              margin-bottom: 0.3rem;
              text-align: center;
              overflow: hidden;
              display: -webkit-box;
              -webkit-line-clamp: 3; // 最多显示3行
              -webkit-box-orient: vertical;
              word-break: break-all;
              line-height: 1.25;
            }

            .classify {
              font-size: 0.8rem;
              color: #575757;
              border-bottom: 0.15rem solid #575757;
            }
            
            .finish-date {
              display: flex;
              align-items: center;
              gap: 0.3rem;
              font-size: 0.8rem;
              color: #575757;
            }
          }

          .icon-box {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .icon-yes {
              width: 100%;
              height: 100%;
              display: flex;
            }

            .icon-other {
              display: flex;
              gap: 0.5rem;
            }

            .iconfont {
              width: 1.85rem;
              height: 1.85rem;
              display: flex;
              align-items: center;
              justify-content: center;
              border-radius: 50%;
              background-color: #fff
            }
          }
        }
      }
    }

    .finished {
      .todo-card {
        background-color: #adf7d1 !important;
      }
    }
  }
}

</style>
